<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\Category as CategoryModel;
use think\facade\View;
use think\response\Json;

class Category extends AdminBase
{
    public function lists(): string
    {
        return View::fetch();
    }

    public function list(): Json
    {
        $categoryBusiness = new \app\common\business\Category($this->websiteCode);
        $categoryInfo     = $categoryBusiness->getAllCategory();
        if (!$categoryInfo['count']) {
            return showList(config(self::_CONFIG_STATUS_ERROR_CODE), '暂无数据', $categoryInfo['rows'], $categoryInfo['count']);
        }

        return showList(config(self::_CONFIG_STATUS_SUCCESS_CODE), 'success', $categoryInfo['rows'], $categoryInfo['count']);
    }

    public function add(): string
    {
        $moduleBusiness = new \app\common\business\Module($this->websiteCode);
        $modules        = $moduleBusiness->getAllModule(['status' => self::_IS_ENABLE_STATUS]);
        View::assign(['modules' => $modules]);

        $pid = $this->request->param('pid', 0, 'intval');
        View::assign(['pid' => $pid]);

        $parentRemark        = ''; // 控制器名称
        $parentCategoryTitle = '顶级栏目'; // 父级栏目名称
        $moduleId            = 0; // 模型ID
        $isRelation          = CategoryModel::IS_DISABLE_RELATION; // 关闭关联
        $parentPage          = CategoryModel::DEFAULT_PAGE_NUM; // 每页记录条数
        $parentCategoryType  = CategoryModel::LIST_PAGE; // 栏目类型
        $parentTarget        = CategoryModel::TOP_TARGET;  // 打开方式
        $parentDefaultTpl    = CategoryModel::DEFAULT_TPL; // 封面模板
        $parentListTpl       = CategoryModel::LISTS_TPL; // 列表模板
        $parentViewTpl       = CategoryModel::VIEW_TPL; // 详情模板
        $parentModuleName    = '';
        $parentAttributes    = [];

        if (!empty($pid)) {
            $categoryBusiness = new \app\common\business\Category($this->websiteCode);
            $category         = $categoryBusiness->findCategoryById($this->cdnDomain, $pid);
            $moduleModel      = new \app\common\business\Module($this->websiteCode);
            $module           = $moduleModel->findModuleById($category['module_id']);
            if (!empty($category)) {
                $moduleId            = $category['module_id'];
                $parentCategoryTitle = $category['title'];
                $isRelation          = $category['is_relation'];
                $parentPage          = $category['page'];
                $parentCategoryType  = $category['type'];
                $parentTarget        = $category['target'];
                $parentRemark        = $category['remark'];
                $parentDefaultTpl    = $category['default_tpl'];
                $parentListTpl       = $category['list_tpl'];
                $parentViewTpl       = $category['view_tpl'];
                $parentAttributes    = $category['attributes'];
                $parentModuleName    = $module['name'];
            }
        }

        View::assign([
            'moduleId'            => $moduleId,
            'parentCategoryTitle' => $parentCategoryTitle,
            'isRelation'          => $isRelation,
            'parentPage'          => $parentPage,
            'parentCategoryType'  => $parentCategoryType,
            'parentTarget'        => $parentTarget,
            'parentRemark'        => $parentRemark,
            'parentDefaultTpl'    => $parentDefaultTpl,
            'parentListTpl'       => $parentListTpl,
            'parentViewTpl'       => $parentViewTpl,
            'parentAttributes'    => $parentAttributes,
            'parentModuleName'    => $parentModuleName,
        ]);

        $attributeBusiness = new \app\common\business\Attribute($this->websiteCode);
        $optionAttributes  = $attributeBusiness->getAllAttribute(['status' => self::_IS_ENABLE_STATUS]);
        View::assign(['optionAttributes' => $optionAttributes]);

        return View::fetch();
    }

    public function doAdd(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $status = $this->request->param('status', 0, 'intval');
        $status = $status == self::_IS_ENABLE_STATUS ? self::_IS_ENABLE_STATUS : self::_IS_DISABLE_STATUS;

        $data = [
            'title'               => $this->request->param('title', '', 'trim'),
            'title_en'            => $this->request->param('title_en', '', 'trim'),
            'pid'                 => $this->request->param('pid', 0, 'intval'),
            'status'              => $status,
            'sort'                => $this->request->param('sort', 0, 'intval'),
            'meta_title'          => $this->request->param('meta_title', '', 'trim'),
            'meta_keyword'        => $this->request->param('meta_keyword', '', 'trim'),
            'meta_description'    => $this->request->param('meta_description', '', 'trim'),
            'module_id'           => $this->request->param('module_id', 0, 'intval'),
            'type'                => $this->request->param('type', 0, 'intval'),
            'is_redirect_child'   => $this->request->param('is_redirect_child', 0, 'intval'),
            'remark'              => $this->request->param('remark', '', 'trim'),
            'page'                => $this->request->param('page', 0, 'intval'),
            'go_url'              => $this->request->param('go_url', '', 'trim'),
            'default_tpl'         => $this->request->param('default_tpl', '', 'trim'),
            'list_tpl'            => $this->request->param('list_tpl', '', 'trim'),
            'view_tpl'            => $this->request->param('view_tpl', '', 'trim'),
            'target'              => $this->request->param('target', '0', 'intval'),
            'image'               => $this->request->param('image', '', 'trim'),
            'seo_url'             => $this->request->param('seo_url', '', 'trim'),
            'introduce_content'   => $this->request->param('introduce_content', '', 'trim'),
            'introduce_video_url' => $this->request->param('introduce_video_url', '', 'trim'),
            'introduce_image'     => $this->request->param('introduce_image', '', 'trim'),
            'note'                => $this->request->param('note', '', 'trim'),
            'note_image'          => $this->request->param('note_image', '', 'trim'),
            'attributes'          => $this->request->param('attributes', '', 'trim'),
            'is_relation'         => $this->request->param('is_relation', CategoryModel::IS_DISABLE_RELATION, 'intval'),
        ];

        $validate = (new \app\admin\validate\Category())->scene('add');
        if (!$validate->check($data)) {
            return show(config("status.error"), $validate->getError());
        }

        $categoryBusiness = new \app\common\business\Category($this->websiteCode);
        if ($categoryBusiness->addCategory($this->cdnDomain, $data)) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), '新增成功');
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), '新增失败');
    }

    public function edit(): string
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            View::assign(['msg' => self::_PARAMETER_ERROR_MESSAGE]);
            return View::fetch('permission/msg');
        }

        $moduleBusiness = new \app\common\business\Module($this->websiteCode);
        $modules        = $moduleBusiness->getAllModule();
        View::assign(['modules' => $modules]);


        $categoryBusiness = new \app\common\business\Category($this->websiteCode);
        $category         = $categoryBusiness->findCategoryById($this->cdnDomain, $id);
        if (empty($category)) {
            View::assign(['msg' => self::_PARAMETER_ERROR_MESSAGE]);
            return View::fetch('permission/msg');
        }
        View::assign(["category" => $category]);

        $attributeBusiness = new \app\common\business\Attribute($this->websiteCode);
        $optionAttributes  = $attributeBusiness->getAllAttribute();
        View::assign(['optionAttributes' => $optionAttributes]);

        return View::fetch();
    }

    public function doEdit(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $id     = $this->request->param('id', 0, 'intval');
        $status = $this->request->param('status', 0, 'intval');
        $status = $status == self::_IS_ENABLE_STATUS ? self::_IS_ENABLE_STATUS : self::_IS_DISABLE_STATUS;

        $data     = [
            'title'               => $this->request->param('title', '', 'trim'),
            'title_en'            => $this->request->param('title_en', '', 'trim'),
            'pid'                 => $this->request->param('pid', 0, 'intval'),
            'status'              => $status,
            'sort'                => $this->request->param('sort', 0, 'intval'),
            'meta_title'          => $this->request->param('meta_title', '', 'trim'),
            'meta_keyword'        => $this->request->param('meta_keyword', '', 'trim'),
            'meta_description'    => $this->request->param('meta_description', '', 'trim'),
            'type'                => $this->request->param('type', 0, 'intval'),
            'is_redirect_child'   => $this->request->param('is_redirect_child', 0, 'intval'),
            'remark'              => $this->request->param('remark', '', 'trim'),
            'page'                => $this->request->param('page', 0, 'intval'),
            'go_url'              => $this->request->param('go_url', '', 'trim'),
            'default_tpl'         => $this->request->param('default_tpl', '', 'trim'),
            'list_tpl'            => $this->request->param('list_tpl', '', 'trim'),
            'view_tpl'            => $this->request->param('view_tpl', '', 'trim'),
            'target'              => $this->request->param('target', '0', 'intval'),
            'image'               => $this->request->param('image', '', 'trim'),
            'is_relation'         => $this->request->param('is_relation', 0, 'intval'),
            'seo_url'             => $this->request->param('seo_url', '', 'trim'),
            'introduce_content'   => $this->request->param('introduce_content', '', 'trim'),
            'introduce_video_url' => $this->request->param('introduce_video_url', '', 'trim'),
            'introduce_image'     => $this->request->param('introduce_image', '', 'trim'),
            'note'                => $this->request->param('note', '', 'trim'),
            'note_image'          => $this->request->param('note_image', '', 'trim'),
            'attributes'          => $this->request->param('attributes', '', 'trim'),
        ];
        $validate = (new \app\admin\validate\Category())->scene('edit');
        if (!$validate->check($data)) {
            return show(config("status.error"), $validate->getError());
        }

        $categoryBusiness = new \app\common\business\Category($this->websiteCode);
        if ($categoryBusiness->updateCategory($this->cdnDomain, $id, $data)) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), '更新成功');
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), '更新失败');
    }

    public function doSort(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $ids  = $this->request->param('ids', '', 'trim');
        $sort = $this->request->param('sort', '', 'trim');
        if (empty($ids) || empty($sort)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PARAMETER_ERROR_MESSAGE);
        }

        $idArr = explode(',', $ids);
        foreach ($idArr as $k => $v) {
            $idArr[$k] = intval($v);
        }

        $sortArr = explode(',', $sort);
        foreach ($sortArr as $k => $v) {
            $sortArr[$k] = intval($v);
        }

        $data = [];
        foreach ($idArr as $k => $v) {
            $data[$v] = $sortArr[$k];
        }

        $categoryBusiness = new \app\common\business\Category($this->websiteCode);
        if ($categoryBusiness->batchUpdateCategorySort($data)) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), '排序成功');
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), '排序失败');
    }

    public function doDelete(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $id = $this->request->param('id', 0, 'intval');
        if ($id == 0) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PARAMETER_ERROR_MESSAGE);
        }

        $categoryBusiness = new \app\common\business\Category($this->websiteCode);
        $res              = $categoryBusiness->deleteCategory($id);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }
    public function doCache(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $categoryBusiness = new \app\common\business\Category($this->websiteCode);
        $res              = $categoryBusiness->clearCategoryCache();
        if ($res) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), 'success');
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), 'success');
    }
}
